<?php

namespace App\HttpController\Oa;


use App\Common\Log;
use App\Common\OA\OA;
use App\HttpController\ControllerBase;
use App\X\EHelper;
use XWX\Common\H;
use XWX\Common\XImage\VCode;

class Login extends ControllerBase
{
    //登陆
    public function index()
    {
        $username = $this->reqParam('username');
        $pwd = $this->reqParam('password');
        $code = $this->reqParam('code');


        $v = new \EasySwoole\Validate\Validate();
        $v->addColumn('username')->required('账号不能为空');
        $v->addColumn('password')->required('请输入6-20位密码');
        if (!$this->validate($v))
        {
            return $this->funcWriteValidate($v);
        }


        //检查验证码
        if ($this->funcIsCheckVCode($username))
        {
            if (H::funcStrIsNullOrEmpty($code))
            {
                return $this->funcWriteErr(-45, '请输入验证码', ['show_code' => true]);
            }

            $vcode = $this->redis()->get(OA::funcVCodeKey__redis($this->funcGetWebIP()));
            if ($code !== $vcode)
            {
                return $this->funcWriteErr(-50, '验证码错误');
            }
        }


        $app_oa = new OA();
        $entity_acc = $app_oa->funcGetAccByUserName($username);
        if ($entity_acc === null)
        {
            return $this->funcWriteErr(-100, '用户不存在');
        }

        if ($entity_acc->acc_lock != 0)
        {
            return $this->funcWriteErr(-150, '帐号已停用');
        }

        $pwd = base64_decode($pwd);
        $pwd_enc = OA::funcGetEncPwd($entity_acc->acc_x_id, $pwd);
        if ($pwd_enc != $entity_acc->acc_pwd)
        {
            //密码不正确，3次需要输验证码

            $show_code = true;
            if (!$this->funcIsCheckVCode($username))
            {
                $show_code = false;

                $this->redis()->incr(OA::funcLoginErrCountKey__redis($username));
                $this->redis()->setTimeout(OA::funcLoginErrCountKey__redis($username), 5 * 60);
            }

            Log::funcLogDebug(__METHOD__, "client:{$pwd_enc},sys:{$entity_acc->acc_pwd}");
            return $this->funcWriteErr(-200, '密码错误', ['show_code' => $show_code]);
        }


        //登陆成功
        $nonce_str = EHelper::funcGetOrderID();
        $sign = OA::funcAdminGetSign($entity_acc->acc_x_id, $entity_acc->acc_id, $nonce_str);


        $data = [
            'OA__x' => $entity_acc->acc_x_id,
            'OA__acc_id' => $entity_acc->acc_id,
            'OA__nonce_str' => $nonce_str,
        ];


        //保存redis
        $redis_key = OA::funcGetLoginKey__redis($sign);
        $this->redis()->set($redis_key, json_encode($data), 3600);


        $this->commonR()->setData('token', base64_encode($redis_key));


        $this->funcWriteCommonR();
    }


    public function test()
    {
        $this->funcWriteCommonR();
    }

    /**
     * 生成验证码
     *
     * @throws \Exception
     */
    public function vcode()
    {
        $code = new VCode();

        mt_srand();
        $vcode = rand(1000, 9999);
        $this->redis()->set(OA::funcVCodeKey__redis($this->funcGetWebIP()), $vcode, 60);

        $res = $code->funcCodeToBytes($vcode);

        $this->response()->withHeader('Content-Type', 'image/png');
        $this->response()->write($res);
    }


    /**
     * 需要验证验证码
     *
     * @param $username
     * @return bool
     * @throws \Exception
     */
    private function funcIsCheckVCode($username)
    {
        $err_count = $this->redis()->get(OA::funcLoginErrCountKey__redis($username));
        if ($err_count >= 2)
        {
            return true;
        }


        return false;
    }
}